package vtt.android.lichphatsongbongda.fragments;

import mobi.mclick.ad.AdsRequest;
import mobi.mclick.ad.AdsView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import vtt.android.library.utils.VttUtils;
import vtt.android.lichphatsongbongda.R;
import vtt.android.lichphatsongbongda.activities.LichPhatSongActivity;
import vtt.android.lichphatsongbongda.database.LpsDAO;
import vtt.android.lichphatsongbongda.dialogs.DialogManager;
import vtt.android.lichphatsongbongda.utils.CommonUtils;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;

/**
 * A placeholder fragment containing a simple view.
 */
@SuppressLint("SimpleDateFormat")
public class LichPhatSongFragment extends BaseWebFragment {
	
	/* define constant */
	private static final String YYYY_MM_DD = "yyyyMMdd";
	private static final String CURRENT_DAY = "current_day";
	public static final String PREF_HOUR = "current_hour";
	private static final String ARG_SECTION_NUMBER = "section_number";
	
	private View mLPSRootView;
	private LpsDAO lpsDao;
	
	private SharedPreferences mSharePref;
    private LichPhatSongActivity mActivity;
	
	/**
	 * Returns a new instance of this fragment for the given section number.
	 */
	public static LichPhatSongFragment newInstance(int sectionNumber) {
		LichPhatSongFragment fragment = new LichPhatSongFragment();
		Bundle args = new Bundle();
		args.putInt(ARG_SECTION_NUMBER, sectionNumber);
		fragment.setArguments(args);
		return fragment;
	}
	
	@Override
	public void onAttach(Activity activity) {
	    super.onAttach(activity);
	    mActivity = (LichPhatSongActivity) activity;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mSharePref = CommonUtils.getSharedPreferences(mParentAct);
		lpsDao = LpsDAO.getInstance(mParentAct);
		lpsDao.open();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		mLPSRootView = inflater.inflate(R.layout.fragment_cm_webview, container, false);
		mProgressBar = (SmoothProgressBar) mLPSRootView.findViewById(R.id.progressbar_loading);

//		// Look up the AdView as a resource and load a request.
//		AdView adView = (AdView) mLPSRootView.findViewById(R.id.adView);
//		// load admob
//		loadAdmob(adView);
		
		/*tạo AdsView*/
        AdsView adsView = new AdsView(getActivity());
        LinearLayout layout = (LinearLayout) mLPSRootView.findViewById(R.id.adsLayout);
        layout.addView(adsView);
        /*load quảng cáo*/
        adsView.loadAds(new AdsRequest());
				
		// init webview
		mWebView = (WebView) mLPSRootView.findViewById(R.id.webView1);
		mWebView.setWebViewClient(new WebClient());
		// init common webview
		initCommonWebview();
		// init custom config
		mWebView.setLongClickable(false);
		mWebView.addJavascriptInterface(new AndroidBridge(), "Android");
		
		mWebView.getSettings().setRenderPriority(RenderPriority.HIGH);
		mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		if (Build.VERSION.SDK_INT >= 11){
		    mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
		}
		
		// load page
		reloadPage();

		return mLPSRootView;
	}
	
    @Override
    protected void reloadPage() {
        if (Build.VERSION.SDK_INT < 14) {
            mWebView.loadUrl(getString(R.string.url_lichphatsong));
        } else {
            mProgressBar.progressiveStart();
            // will be empty at first time
            if("".equals(lpsDao.loadCacheData())){
                mWebView.loadUrl(getString(R.string.url_lichphatsong));
            } else {
                mWebView.loadUrl(getString(R.string.url_lichphatsong_local));
            }
            // get new data in background
            new KenhTvTask().execute(getString(R.string.url_lichphatsong));
        }
    }
    
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();
        inflater.inflate(R.menu.menu_kenhtv, menu);
    }
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		log.d("VTT>>> action_refresh" + "");
		switch (item.getItemId()) {
		case R.id.action_watch_tv:
		    // open page watch TV
		    ((LichPhatSongActivity)mParentAct).openPageTV();
		    return true;
		case R.id.action_refresh:
			if(!VttUtils.checkNetworkConnection(mParentAct)){
				mDialogManager.showCommonDialog(DialogManager.DIALOG_TYPE_INFOR, getString(R.string.msg_title_notice), getString(R.string.msg_network_error), null);
				return true;
			}
			if(mWebView != null){
				// reset data trong db de webview lay lai du lieu moi  
				//log.d("VTT>>> reset data in cache ");
				//lpsDao.saveCacheData("");
			    // reset Kenh TV hour
	            mSharePref.edit().putLong(LichPhatSongFragment.PREF_HOUR, -1).commit();
	            
				reloadPage();
			}
			return true;
		}
		
		return super.onOptionsItemSelected(item);
	}
	
	class WebClient extends WebViewClient {

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
//			mProgressBar.setVisibility(View.VISIBLE);
//			mProgressBar.setProgress(0);
			mProgressBar.progressiveStart();
			super.onPageStarted(view, url, favicon);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			
            if (Build.VERSION.SDK_INT < 14) {
                StringBuffer injectScript = new StringBuffer();
                injectScript.append("javascript: ");
                injectScript.append("document.getElementById('div_content1').style.display = 'none'; ");
                injectScript.append("document.getElementById('div_content2').style.display = 'none'; ");
                injectScript.append("document.getElementById('div_content3').style.display = 'none'; ");
                injectScript.append("document.getElementById('ads_topmenu_2').style.display = 'none'; ");
                injectScript.append("document.getElementById('google_ad').style.display = 'none'; ");

                view.loadUrl(injectScript.toString());
            }
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			log.d("VTT>>> url " + url);
			return super.shouldOverrideUrlLoading(view, url);
		}
	}
	
	/*
	 * Android bridge
	 */
	class AndroidBridge {
		
	    @JavascriptInterface
		public void log(String tag, String msg){
			log.d("VTT>>> " + tag + " : " + msg);
		}
		
		@JavascriptInterface
        public String getHtmlData(){
            return lpsDao.loadCacheData();
        }
	}
	
	// save LPS cache data
    public void saveData(String data){
        lpsDao.saveCacheData(data);
        long hour = System.currentTimeMillis() / 1000 / 60 / 60;
        mSharePref.edit().putLong(PREF_HOUR, hour).commit();
    }
    
    /**
     * get LPS cache data every 1 hour
     * @return true
     */
    public boolean isLoadLpsDataFromCache(){
        long curHour = System.currentTimeMillis() / 1000 / 60 / 60;
        long oldHour = mSharePref.getLong(PREF_HOUR, -1);
         
        // if current hour > old hour thi se kiem tra lay data trong db
        if(oldHour != -1 && (curHour - oldHour < 2)){
            log.d("VTT>>> isLoadLpsDataFromCache = true ");
            return true;
        }
        log.d("VTT>>> isLoadLpsDataFromCache = false ");
        
        return false;
    }
	
    /**
     * get kenh phat song data
     * @author VinhTT
     */
    private class KenhTvTask extends AsyncTask<String, Void, Boolean> {
 
        @Override
        protected Boolean doInBackground(String... params) {
            log.d("VTT>>> " + "doInBackground");
            try {
                if(!isLoadLpsDataFromCache()){
                    // Connect to the web site
                    Document document = Jsoup.connect(params[0]).get();
                    // Using Elements to get the Meta data
                    Elements kenhTvTable = document.select("div.Background_trandau");
                    //log.d("VTT>>> kenhTvTable.html().length() " + kenhTvTable.html().length());
                    // save cache data
                    saveData(kenhTvTable.html());
                    return true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }
 
        @Override
        protected void onPostExecute(Boolean result) {
            if(getActivity() == null || mWebView == null){
                return;
            }
            log.d("VTT>>> " + "onPostExecute result " + result);
            if(result){
                log.d("VTT>>> " + "onPostExecute force reload new data");
                mWebView.loadUrl(getString(R.string.url_lichphatsong_local));
            }
        }
    }
}